import random
import sys

from django.db.models import Count, Q
from rest_framework.generics import get_object_or_404

from rest_api.utils.common_util import addExp, checkName
from rest_api.utils.lucky_sport_pagination import LuckyScportPagination

sys.setrecursionlimit(1000000)

import requests

from rest_framework import generics

from databases.serializers import *
from rest_api.serializers import *
from rest_api.utils.date_util import Get_Yesterday, Get_Now
from rest_api.utils.memcache_utils import create_memcache
from rest_api.utils.page_util import page_info
from rest_api.utils.upload import upload


class PostSendMessage(generics.CreateAPIView):
    """
    发送短信接口(已测试)
    """
    queryset = AppUser.objects.all()
    serializer_class = PostSendMessageSerializer
    permission_validate = False

    def post(self, request, *args, **kwargs):
        data = request.data
        _phone = data.get('phone')
        url = 'http://sms.253.com/msg/send'
        # un = 'N8369799'
        un = 'CN4153626'
        # pw = r'9BRiLqyrnp2ebd'
        pw = r'Sxkl0RrGta1401'
        phone_number = _phone
        code = str(random.randint(100000, 999999))
        _code = str(123456)
        msg = '【走运啦】 验证码 %s，如非本人操作，请检查您的软件账号 。 ' % code
        _msg = '【走运啦】 验证码 %s，如非本人操作，请检查您的软件账号 。 ' % _code
        rd = 1
        _client = create_memcache()
        data = {}
        if phone_number == '13732196407':
            _client.set('message_' + _phone, _code)
            data = {
                'un': un,
                'pw': pw,
                'phone': phone_number,
                'msg': _msg,
                'rd': rd
            }
        else:
            _client.set('message_' + _phone, code)
            data = {
                'un': un,
                'pw': pw,
                'phone': phone_number,
                'msg': msg,
                'rd': rd
            }

        _rq = requests.session()
        _rq.keep_alive = False

        res = _rq.get(url, params=data)
        return Response(status.HTTP_200_OK)


class PostRegister(generics.CreateAPIView):
    """
    注册APP的接口(已测试)
    """
    queryset = AppUser.objects.all()
    serializer_class = PostRegisterSerializer
    permission_validate = False

    def create(self, request, *args, **kwargs):
        data = request.data
        _phone = data.get('phone')
        _password = data.get('password')
        _code = data.get('code')
        _client = create_memcache()
        _message = eval(_client.get('message_' + _phone))
        return_dict = {}
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid(raise_exception=True):
            try:
                _user_app = AppUser.objects.get(user_account=_phone)
                return_dict['detail'] = {"message": "该账户已注册"}
                return Response(return_dict, status=status.HTTP_400_BAD_REQUEST)
            except:
                if _message == int(_code):
                    _user = AppUser()
                    _user.user_account = _phone
                    _user.password = _password
                    _user.save()
                    _serializer = AppUserSerializer(_user)
                    return Response(_serializer.data, status=status.HTTP_201_CREATED)
                else:
                    return_dict['detail'] = {"message": "手机验证码错误"}
                    return Response(return_dict, status=status.HTTP_400_BAD_REQUEST)


class PostQQThirdLogin(generics.CreateAPIView):
    """
    第三方登录
    type: 0 :QQ 1: 微信 2：微博
    """
    queryset = AppUser.objects.all()
    serializer_class = PostThirdLoginSerializer

    permission_validate = False

    def create(self, request, *args, **kwargs):
        data = request.data
        _qq = data.get('open_id')
        _type = int(data.get('type'))
        _uuid = uuid.uuid1()
        try:
            serializer = self.get_serializer(data=request.data)
            if serializer.is_valid(raise_exception=True):
                try:
                    if _type == 0:
                        _user = AppUser.objects.get(qq_openid=_qq)
                        try:
                            _token = Token.objects.get(user=_user)
                            _token.token = _uuid
                            _token.save()
                        except:
                            _token = Token()
                            _token.token = _uuid
                            _token.user = _user
                            _token.save()
                        _serializer = AppUserSerializer(_user)
                        return Response(_serializer.data, status=status.HTTP_201_CREATED)
                    elif _type == 1:
                        _user = AppUser.objects.get(wechart_openid=_qq)
                        try:
                            _token = Token.objects.get(user=_user)
                            _token.token = _uuid
                            _token.save()
                        except:
                            _token = Token()
                            _token.token = _uuid
                            _token.user = _user
                            _token.save()
                        _serializer = AppUserSerializer(_user)
                        return Response(_serializer.data, status=status.HTTP_201_CREATED)
                    else:
                        _user = AppUser.objects.get(weibo_openid=_qq)
                        try:
                            _token = Token.objects.get(user=_user)
                            _token.token = _uuid
                            _token.save()
                        except:
                            _token = Token()
                            _token.token = _uuid
                            _token.user = _user
                            _token.save()
                        _serializer = AppUserSerializer(_user)
                        return Response(_serializer.data, status=status.HTTP_201_CREATED)
                except:
                    if _type == 0:
                        _user = AppUser()
                        _user.qq_openid = _qq
                        _user.save()
                        try:
                            _token = Token.objects.get(user=_user)
                            _token.token = _uuid
                            _token.save()
                        except:
                            _token = Token()
                            _token.token = _uuid
                            _token.user = _user
                            _token.save()
                        _serializer = AppUserSerializer(_user)
                        return Response(_serializer.data, status=status.HTTP_201_CREATED)
                    elif _type == 1:
                        _user = AppUser()
                        _user.wechart_openid = _qq
                        _user.save()
                        try:
                            _token = Token.objects.get(user=_user)
                            _token.token = _uuid
                            _token.save()
                        except:
                            _token = Token()
                            _token.token = _uuid
                            _token.user = _user
                            _token.save()
                        _serializer = AppUserSerializer(_user)
                        return Response(_serializer.data, status=status.HTTP_201_CREATED)
                    else:
                        _user = AppUser()
                        _user.weibo_openid = _qq
                        _user.save()
                        try:
                            _token = Token.objects.get(user=_user)
                            _token.token = _uuid
                            _token.save()
                        except:
                            _token = Token()
                            _token.token = _uuid
                            _token.user = _user
                            _token.save()
                        _serializer = AppUserSerializer(_user)
                        return Response(_serializer.data, status=status.HTTP_201_CREATED)
        except Exception as e:
            return Response(e.__repr__(), status=status.HTTP_400_BAD_REQUEST)


class PostLogin(generics.CreateAPIView):
    """
    用户登录接口
    """
    queryset = AppUser.objects.all()
    serializer_class = PostLoginSerializer

    permission_validate = False

    def post(self, request, *args, **kwargs):
        data = request.data
        return_dict = {}
        _phone = data.get('phone')
        _password = data.get('password')

        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid(raise_exception=True):

            try:
                _player = AppUser.objects.get(user_account=_phone)
                if _player.password == _password:
                    _uuid = uuid.uuid1()
                    try:
                        _token = Token.objects.get(user=_player)
                        _token.token = _uuid
                        _token.save()
                    except:
                        _token = Token()
                        _token.token = _uuid
                        _token.user = _player
                        _token.save()
                    _serializer = AppUserSerializer(_player)
                    return Response(_serializer.data, status=status.HTTP_200_OK)
                else:
                    return_dict['detail'] = {"message": "密码错误"}
                    return Response(return_dict, status=status.HTTP_400_BAD_REQUEST)
            except Exception as e:
                return_dict['detail'] = {"message": "该手机号尚未注册"}
                return Response(return_dict, status=status.HTTP_400_BAD_REQUEST)


class BindingPhone(generics.CreateAPIView):
    queryset = AppUser.objects.all()
    serializer_class = PostRegisterSerializer

    def post(self, request, *args, **kwargs):
        data = request.data
        _id = request.app_user.id
        _password = data.get('password')
        _code = data.get('code')
        _phone = data.get('phone')
        _client = create_memcache()
        _message = eval(_client.get('message_' + _phone))
        return_dict = {}
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid(raise_exception=True):
            try:
                _user_app = AppUser.objects.get(user_account=_phone)
                return_dict['detail'] = {"message": "该账户已注册"}
                return Response(return_dict, status=status.HTTP_400_BAD_REQUEST)
            except:
                _app_user = AppUser.objects.get(pk=_id)
                if _message == int(_code):
                    _app_user.user_account = _phone
                    _app_user.password = _password
                    _app_user.save()
                    _serializer = AppUserSerializer(_app_user)
                    return Response(_serializer.data, status=status.HTTP_201_CREATED)
                else:
                    return_dict['detail'] = {"message": "手机验证码错误"}
                    return Response(return_dict, status=status.HTTP_400_BAD_REQUEST)


class PostForgetPassword(generics.CreateAPIView):
    """
    用户忘记密码
    """
    queryset = AppUser.objects.all()
    serializer_class = PostForgetSerializer
    permission_validate = False

    def post(self, request, *args, **kwargs):
        return_dict = {}
        data = request.data
        _code = data.get('code')
        _password = data.get('password')
        _phone = data.get('phone')
        _client = create_memcache()
        _message = eval(_client.get('message_' + _phone))
        serializer = self.get_serializer(data=request.data)
        try:
            _user = AppUser.objects.get(user_account=_phone)
            if _message == int(_code):
                _user.password = _password
                _user.save()
                return_dict['result'] = {"message": "更新成功"}
                return Response(return_dict, status=status.HTTP_200_OK)
            else:
                return_dict['detail'] = {"message": "验证码不正确"}
                return Response(return_dict, status=status.HTTP_400_BAD_REQUEST)
        except:
            return_dict['detail'] = {"message": "更新失败"}
            return Response(return_dict, status=status.HTTP_400_BAD_REQUEST)


class PostResetPassword(generics.CreateAPIView):
    """
    用户重置密码
    """
    queryset = AppUser.objects.all()
    serializer_class = PostResetSerializer

    def post(self, request, *args, **kwargs):
        return_dict = {}
        data = request.data
        _old = data.get('old')
        _password = data.get('new')
        _app_user = request.app_user
        serializer = self.get_serializer(data=request.data)
        try:

            if _app_user.password == _old:
                _app_user.password = _password
                _app_user.save()
                return_dict['result'] = {"message": "更新成功"}
                return Response(return_dict, status=status.HTTP_200_OK)
            else:
                return_dict['detail'] = {"message": "老密码不正确"}
                return Response(return_dict, status=status.HTTP_400_BAD_REQUEST)
        except:
            return_dict['detail'] = {"message": "更新失败"}
            return Response(return_dict, status=status.HTTP_400_BAD_REQUEST)


class PostLogout(generics.CreateAPIView):
    """
    用户退出接口
    """
    queryset = AppUser.objects.all()
    serializer_class = AppUserSerializer

    def post(self, request, *args, **kwargs):
        return_dict = {}
        _app_user = request.app_user
        try:
            app_token = request.META.get('HTTP_APPTOKEN', None)
            token = Token.objects.get(
                token=app_token
            )
            token.delete()
            return_dict['result'] = {"message": "退出成功"}
            return Response(return_dict, status=status.HTTP_200_OK)
        except:
            return_dict['detail'] = {"message": "退出失败"}
            return Response(return_dict, status=status.HTTP_200_OK)


class PostLoginByCode(generics.CreateAPIView):
    """
    验证码登录
    """
    queryset = AppUser.objects.all()
    serializer_class = PostLoginCodeSerializer

    permission_validate = False

    def post(self, request, *args, **kwargs):
        data = request.data
        return_dict = {}
        _phone = data.get('phone')
        _password = data.get('code')
        _client = create_memcache()
        _message = eval(_client.get('message_' + _phone))
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid(raise_exception=True):
            try:
                _player = AppUser.objects.get(user_account=_phone)
                if str(_message) == _password:
                    _uuid = uuid.uuid1()
                    try:
                        _token = Token.objects.get(user=_player)
                        _token.token = _uuid
                        _token.save()
                    except:
                        _token = Token()
                        _token.token = _uuid
                        _token.user = _player
                        _token.save()
                    _serializer = AppUserSerializer(_player)
                    return Response(_serializer.data, status=status.HTTP_200_OK)
                else:
                    return_dict['detail'] = {"message": "验证码错误"}
                    return Response(return_dict, status=status.HTTP_400_BAD_REQUEST)
            except Exception as e:
                return_dict['detail'] = {"message": "该手机号尚未注册"}
                return Response(return_dict, status=status.HTTP_400_BAD_REQUEST)


class PostUserInfo(generics.CreateAPIView):
    """
    用户完善个人资料
    """
    queryset = UserInfo.objects.all()
    serializer_class = PostSaveUserInfoSerializer

    def create(self, request, *args, **kwargs):
        data = request.data
        _app_user = request.app_user
        return_dict = {}
        _name = data.get('nick_name')
        _portrait = data.get('portrait')
        _sex = data.get('sex')
        _height = data.get('height')
        _weight = data.get('weight')
        _year = data.get('year')
        _month = data.get('month')
        _city = data.get('city')
        _target = data.get('target_weight')
        serializer = self.get_serializer(data=request.data)
        _year_now = datetime.datetime.now().year
        _month_now = datetime.datetime.now().month
        try:
            if serializer.is_valid(raise_exception=True):
                try:
                    _user = UserInfo.objects.get(user=_app_user)
                    _user_infos = UserInfo.objects.filter(nick_name=_name).exclude(user=_app_user)
                    if not checkName(_name):
                        return_dict['detail'] = {"message": "禁止使用的昵称，请重新填写"}
                        return Response(return_dict, status=status.HTTP_400_BAD_REQUEST)
                    if len(_user_infos) > 0:
                        return_dict['detail'] = {"message": "昵称已被使用，请重新填写"}
                        return Response(return_dict, status=status.HTTP_400_BAD_REQUEST)

                except Exception as e:
                    _user = UserInfo()

                _user.user = _app_user
                _user.nick_name = _name
                _user.target_weight = _target
                _user.portrait = _portrait
                _user.sex = int(_sex)
                _user.height = _height
                _user.weight = _weight

                _user.birth_year = int(_year)
                _user.birth_month = int(_month)
                if _month_now >= int(_month):
                    _user.age = _year_now - int(_year)
                else:
                    _user.age = _year_now - int(_year) - 1

                _user.city = _city
                _body_data = data.copy()
                _user.save()
                _body_dimension = _body_data.get('body_dimension', None)
                if not _body_dimension:
                    _data = request.data.copy()
                    _data['user'] = _user
                    _body_serializer = UserBodyDimensionSerializer(data=_data)
                    if _body_serializer.is_valid():
                        _body_serializer.save()
                    # else:
                    #     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
                _serializer = UserInfoSerializer(_user)
                return Response(_serializer.data, status=status.HTTP_201_CREATED)
            else:
                return_dict['detail'] = {"message": "用户数据有误"}
                return Response(return_dict, status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            if e.args[0] == 1062:
                return_dict['detail'] = {"message": "昵称已被使用，请重新填写"}
                return Response(return_dict, status=status.HTTP_400_BAD_REQUEST)

            print(e)
            return_dict['detail'] = {"message": "服务器异常"}
            return Response(return_dict, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class PostSignUp(generics.CreateAPIView):
    """
    每日签到（还缺少经验规则的加入）request.query_param.get('id')
    """
    queryset = UserInfo.objects.all()
    serializer_class = UserInfoSerializer

    # permission_validate = False

    def post(self, request, *args, **kwargs):
        _user_info = request.app_user
        _yes = Get_Yesterday()
        _now = Get_Now()
        return_dict = {}
        try:
            # 今天有没有打卡
            UserSign.objects.get(sign_date=_now, user=_user_info.userinfo)
            return_dict['detail'] = {"message": "太棒了！您今天已经打过卡了，请明天再来打卡哦！"}
            return Response(return_dict, status=status.HTTP_400_BAD_REQUEST)
        except:
            try:
                _user = _user_info.userinfo
                _sign = UserSign()
                _sign.user_id = _user_info.userinfo.id
                _sign.sign_date = _now
                _sign.sign_day = datetime.datetime.now().day
                _sign.sign_month = datetime.datetime.now().month
                _sign.sign_year = datetime.datetime.now().year
                _sign.save()
                try:
                    UserSign.objects.get(sign_date=_yes, user_id=_user_info.userinfo.id)
                    _user.continuity_sign = _user.continuity_sign + 1
                    if _user.medals is None:
                        if _user.continuity_sign >= 7:
                            _user.medals = '1'
                    else:
                        if '1' not in _user.medals:
                            if _user.continuity_sign >= 7:
                                _user.medals = _user.medals + ',1'
                except:
                    _user.continuity_sign = 1
                _user.save()
                _serializer = UserInfoSerializer(_user)
                return_dict['result'] = {"point": addExp(_user, 1), "share": _serializer.data}
                return Response(return_dict, status=status.HTTP_200_OK)
            except:
                return_dict['detail'] = {"message": "用户信息未填写填写"}
                return Response(return_dict, status=status.HTTP_400_BAD_REQUEST)


class GetMonthSign(generics.ListAPIView):
    """
    获取指定月份所有签到的方法
        _month = request.query_params.get('month')
        _year = request.query_params.get('year')
    """
    queryset = UserSign.objects.all()
    serializer_class = UserSignSerializer

    def get(self, request, *args, **kwargs):
        _id = request.app_user.userinfo.id
        _month = request.query_params.get('month')
        _year = request.query_params.get('year')
        _sign = UserSign.objects.filter(sign_year=_year,
                                        sign_month=_month, user_id=_id)
        _serializer = UserSignSerializer(_sign, many=True)
        return Response(_serializer.data, status=status.HTTP_200_OK)


class QQRedirect(generics.ListAPIView):
    """
    QQ登录回调接口
    """
    queryset = AppUser.objects.all()
    serializer_class = AppUserSerializer

    def get(self, request, *args, **kwargs):
        try:
            _code = request.query_params.get('')
        except Exception as e:
            return Response(e.__dict__)


class UpdatePic(generics.CreateAPIView):
    """
    上传文件通用
    """
    queryset = UserInfo.objects.all()
    serializer_class = UserInfoSerializer

    permission_validate = False

    def post(self, request, *args, **kwargs):
        img = request.FILES['img']
        url = upload(img)
        return_dict = {"url": url}
        return Response(return_dict)


class UpdateVideo(generics.CreateAPIView):
    """
    上传视频通用
    文件标签：'video'
    """
    queryset = UserInfo.objects.all()
    serializer_class = UserInfoSerializer

    permission_validate = False

    def post(self, request, *args, **kwargs):
        img = request.FILES['video']
        url = upload(img)
        return_dict = {"url": url}
        return Response(return_dict)


class GetTrainByPage(generics.ListAPIView):
    """
    获取所有的训练 pageSize pageNo
    """
    queryset = Training.objects.filter(is_delete=False).order_by('-is_top', 'order')
    serializer_class = TrainingSerializer
    pagination_class = LuckyScportPagination


class GetWarmTrain(generics.ListAPIView):
    """
    获取当前热身视频
    """
    queryset = Training.objects.all()
    serializer_class = TrainingSerializer

    def get(self, request, *args, **kwargs):
        return_dict = {}
        try:
            _warm_train = Training.objects.get(is_warm_up=True, is_delete=False)
            _serializer = TrainingSerializer(_warm_train)
            return Response(_serializer.data, status=status.HTTP_200_OK)
        except:
            return_dict['detail'] = {"message": "当前没有热身训练视频"}
            return Response(return_dict, status=status.HTTP_400_BAD_REQUEST)


class GetTrainRecommendList(generics.ListAPIView):
    """
    获取所有的已推荐的训练
    """
    queryset = JoinTrainRecord.objects.all()
    serializer_class = JoinTrainRecordSerializer

    def list(self, request, *args, **kwargs):
        _user = request.app_user.userinfo.id
        _info_list = JoinTrainRecord.objects.filter(user_id=_user).values_list('train_id')
        _list = Training.objects.filter(is_delete=False, pk__in=_info_list)
        _serializer = TrainingSerializer(_list, many=True)
        return Response(_serializer.data, status=status.HTTP_200_OK)


class GetTrainDetail(generics.ListAPIView):
    """
    获取训练详情
    """
    queryset = Training.objects.all()
    serializer_class = TrainingSerializer

    def list(self, request, *args, **kwargs):
        _id = kwargs.get('PK')
        return_dict = {}
        try:
            _list = Training.objects.get(pk=_id)
            _serializer = TrainingSerializer(_list)
            _list.browse_num = _list.browse_num + 1
            _list.save()
            _join = JoinTrainRecord()
            _join.user_id = request.app_user.userinfo.id
            _join.train_id = _id
            _join.save()
            return Response(_serializer.data, status=status.HTTP_200_OK)
        except:
            return_dict['detail'] = {"message": "该训练未找到"}
            return Response(return_dict, status=status.HTTP_200_OK)


class GetTrainByCategory(generics.ListAPIView):
    """
    获取该训练类目下所有的训练
    """
    queryset = Training.objects.all()
    serializer_class = TrainingSerializer

    def list(self, request, *args, **kwargs):
        _id = kwargs.get('category')
        _list = Training.objects.filter(train_category_id=_id)
        _serializer = TrainCategorySerializer(_list, many=True)
        return Response(_serializer.data, status=status.HTTP_200_OK)


class GetTrainingList(generics.ListAPIView):
    """
    获取该训练类目下所有的训练
    """
    queryset = Training.objects.all()
    serializer_class = TrainingSerializer

    def list(self, request, *args, **kwargs):
        _list = Training.objects.filter(is_delete=False)
        _serializer = TrainingSerializer(_list, many=True)
        return Response(_serializer.data, status=status.HTTP_200_OK)


class DelReleaseMessage(generics.DestroyAPIView):
    """
    删除帖子
    """

    def delete(self, request, *args, **kwargs):
        _affair_record = AffairsRecord.objects.get(pk=kwargs['pk'])
        _affair_record.is_delete = True
        _affair_record.save()
        return Response(status=status.HTTP_200_OK)


class ReleaseMessageList(generics.ListAPIView):
    """
    ?pageSize=10&pageNo=1 获取我的帖子
    """
    serializer_class = AffairsRecordSerializer
    queryset = AffairsRecord.objects.all()

    def get(self, request, *args, **kwargs):
        _user = request.app_user.userinfo.id
        _pageSize = request.query_params.get('pageSize')
        _pageNum = request.query_params.get('pageNo')
        _affairs = AffairsRecord.objects.filter(user_id=_user, is_delete=False).order_by("-create_time", )
        _user_info = request.app_user.userinfo
        _user_info.flush_homepage_time = datetime.datetime.now()
        _user_info.save()

        for _affair in _affairs:
            try:
                _thumb = ThumbRecord.objects.get(affair_id=_affair.id, user_id=_user)
                _affair.is_thumb = True
            except:
                _affair.is_thumb = False
        _serializers = self.get_serializer(_affairs, many=True)
        _list = page_info(_serializers.data, _pageSize, _pageNum)
        return Response(_list, status=status.HTTP_200_OK)


class PostReleaseMessage(generics.CreateAPIView):
    """
    发布帖子的通用接口
    """
    queryset = AffairsRecord.objects.all()
    serializer_class = PostReleaseMessageSerializer

    def create(self, request, *args, **kwargs):
        data = request.data
        _user = request.app_user.userinfo.id
        _text = data.get('text')
        _photo = data.get('photo')
        _present = data.get('present')
        _longitude = data.get('longitude', None)
        if not _longitude:
            _longitude = None
        _latitude = data.get('latitude', None)
        if not _latitude:
            _latitude = None
        return_dict = {}
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid(raise_exception=True):
            _affairsRecord = AffairsRecord()
            _affairsRecord.user_id = _user
            _affairsRecord.affair_text = _text
            _affairsRecord.affair_photo = _photo
            _affairsRecord.present_weight = _present
            _affairsRecord.longitude = _longitude
            _affairsRecord.latitude = _latitude
            _affairsRecord.save()
            _serializer = AffairsRecordSerializer(_affairsRecord)
            addExpMsg = addExp(request.app_user.userinfo, 8)
            return_dict['result'] = {"point": addExpMsg, "affair": _serializer.data}
            return Response(return_dict, status=status.HTTP_200_OK)


class GetAffairByUser(generics.ListAPIView):
    """
    获取我发的帖子列表
    """
    queryset = AffairsRecord.objects.all()
    serializer_class = AffairsRecordSerializer

    def list(self, request, *args, **kwargs):
        _user = request.app_user.userinfo.id
        _affairsRecord = AffairsRecord.objects.filter(user_id=_user, is_delete=False)
        _serializer = AffairsRecordSerializer(_affairsRecord, many=True)
        return Response(_serializer.data, status=status.HTTP_200_OK)


class PostThumbsMessage(generics.CreateAPIView):
    """
    帖子点赞/取消点赞的接口
    """
    queryset = ThumbRecord.objects.all()
    serializer_class = ThumbRecordSerializer

    def post(self, request, *args, **kwargs):
        _affair_id = kwargs.get('affair')
        _user_info_id = request.app_user.userinfo.id
        return_dict = {}
        try:
            return_dict['detail'] = {"message": "该条帖子您已点赞"}
            ThumbRecord.objects.get(user_id=_user_info_id, affair_id=_affair_id)
            return Response(return_dict, status=status.HTTP_400_BAD_REQUEST)
        except ThumbRecord.DoesNotExist:
            affair = AffairsRecord.objects.get(pk=_affair_id)
            _comment = ThumbRecord()
            _comment.user_id = _user_info_id
            _comment.affair_id = _affair_id
            _comment.save()
            affair.thumbs_num = affair.thumbs_num + 1
            affair.save()
        # _serializer = CommentRecordSerializer(_comment)
        addExpMsg = addExp(request.app_user.userinfo, 7)
        return_dict['result'] = {"point": addExpMsg, "message": "点赞成功"}
        return Response(return_dict, status=status.HTTP_200_OK)


class PostAffairDetail(generics.CreateAPIView):
    """
    帖子详情（浏览量增加）
    """
    queryset = AffairsRecord.objects.all()
    serializer_class = AffairsRecordSerializer

    def post(self, request, *args, **kwargs):
        _affair = kwargs.get('affair')
        return_dict = {}
        _user = request.app_user.userinfo.id
        try:
            _aff = AffairsRecord.objects.get(pk=_affair)
            try:
                _thumb = ThumbRecord.objects.get(affair_id=_affair, user_id=_user)
                _aff.browse_num = _aff.browse_num + 1
                _aff.save()
                serializer = AffairsRecordSerializer(_aff)
                return_dict = {"affair": serializer.data, "is_thumb": True}
                return Response(return_dict, status=status.HTTP_200_OK)
            except:
                _aff.browse_num = _aff.browse_num + 1
                _aff.save()
                serializer = AffairsRecordSerializer(_aff)
                return_dict = {"affair": serializer.data, "is_thumb": False}
                return Response(return_dict, status=status.HTTP_200_OK)
        except Exception as e:
            return_dict['detail'] = {"message": "帖子未找到"}
            return Response(return_dict, status=status.HTTP_200_OK)


class GetCommentByFirstLevel(generics.ListAPIView):
    """
    根据帖子一级评论获取所有回复
    """
    permission_validate = False
    queryset = CommentRecord.objects.all()
    serializer_class = CommentFirstRecordSerializer

    def list(self, request, *args, **kwargs):
        _affair = kwargs.get('PK')
        return_dict = {}
        try:
            # _list = CommentRecord.objects.get(pk=_affair)
            _list_ = CommentRecord.objects.filter(top=_affair)
            _serializer = CommentFirstRecordSerializer(_list_, many=True)
            return Response(_serializer.data, status=status.HTTP_200_OK)
        except:
            return_dict['detail'] = {"message": "评论未找到"}
            return Response(return_dict, status=status.HTTP_400_BAD_REQUEST)


class GetCommentByAffair(generics.ListAPIView):
    """
    根据帖子 获取所有评论
    """
    queryset = CommentRecord.objects.filter(level=1)
    serializer_class = CommentRecordSerializer
    permission_validate = False

    def list(self, request, *args, **kwargs):
        _id = kwargs.get('PK')
        _obj = CommentRecord.objects.filter(affair_id=_id, level=1)
        serializer = CommentRecordSerializer(_obj, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)


class GetAllAffairPage(generics.ListAPIView):
    """
    获取所有帖子的方法
    """
    queryset = AffairsRecord.objects.filter(is_delete=False).order_by('-create_time')
    serializer_class = AffairsRecordSerializer
    pagination_class = LuckyScportPagination

    def list(self, request, *args, **kwargs):
        _user = request.app_user.userinfo.id
        _user_info = request.app_user.userinfo
        _user_info.flush_affair_time = datetime.datetime.now()
        _user_info.save()
        queryset = self.filter_queryset(self.get_queryset())
        page = self.paginate_queryset(queryset)
        if page is not None:
            for _affair in page:
                try:
                    ThumbRecord.objects.get(affair_id=_affair.id, user_id=_user)
                    _affair.is_thumb = True
                except:
                    _affair.is_thumb = False
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
            # return Response(serializer.data,status=status.HTTP_200_OK)
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)


class GetRecommendAffairPage(generics.ListAPIView):
    """
    获取所有推荐帖子的方法
     request.query_params.get('pageSize')
request.query_params.get('pageNo')
    """
    queryset = AffairsRecord.objects.all()
    serializer_class = AffairsRecordSerializer

    def list(self, request, *args, **kwargs):
        _user = request.app_user.userinfo.id
        _info_list = AffairsRecord.objects.filter(is_delete=False, is_recommend=True).order_by('-create_time')
        _pageSize = request.query_params.get('pageSize')
        _pageNum = request.query_params.get('pageNo')
        for _affair in _info_list:
            try:
                _thumb = ThumbRecord.objects.get(affair_id=_affair.id, user_id=_user)
                _affair.is_thumb = True
            except:
                _affair.is_thumb = False
        _list = page_info(AffairsRecordSerializer(_info_list, many=True).data, _pageSize, _pageNum)
        return Response(_list, status=status.HTTP_200_OK)


class CreateCommentByAffair(generics.CreateAPIView):
    """
    创建评论
    """
    queryset = CommentRecord.objects.filter(level=1)
    serializer_class = PostCreateCommentSerializer

    def create(self, request, *args, **kwargs):
        _id = request.app_user.userinfo.id
        data = request.data
        _father = data.get('father')
        _affair = data.get('affair')
        _text = data.get('text')
        _top = data.get('top')
        return_dict = {}
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid(raise_exception=True):
            try:
                _record = CommentRecord.objects.get(pk=_father)
                CommentRecord.objects.get(pk=_top)
                _comment = CommentRecord()
                _comment.user_id = _id
                _comment.father = _record
                _comment.level = _record.level + 1
                _comment.comment_text = _text
                _comment.affair_id = _affair
                _comment.top = _top
                _comment.save()
            except CommentRecord.DoesNotExist:
                _comment = CommentRecord()
                _comment.user_id = _id
                _comment.level = 1
                _comment.comment_text = _text
                _comment.affair_id = _affair
                _comment.save()
            _serializer = CommentRecordSerializer(_comment)
            addExpMsg = addExp(request.app_user.userinfo, 6)
            return_dict['result'] = {"point": addExpMsg, "comment": _serializer.data}
            return Response(return_dict, status=status.HTTP_200_OK)


class CommonProble(generics.ListCreateAPIView):
    """
    常见问题 查询 新增
    查询没有问题具体内容,
    新增需要title,content,sort
    """
    permission_validate = False
    queryset = CommonProblemModel.objects.filter(is_delete=False)
    serializer_class = CommonProblemSerializer
    pagination_class = LuckyScportPagination

    def post(self, request, *args, **kwargs):
        _common_problem_type = CommonProblemTypeModel.objects.get(pk='1')
        _common_problem = CommonProblemModel()
        _common_problem.title = request.POST['title']
        _common_problem.type = _common_problem_type
        _common_problem.content = request.POST['content']
        _common_problem.sort_no = request.POST.get('sort_no', 0)
        _common_problem.save()
        _serializer = self.get_serializer(_common_problem)
        return Response(_serializer.data, status=status.HTTP_201_CREATED)


class GetCommonProbleContent(generics.ListAPIView):
    permission_validate = False

    """
    获取常见问题详细信息
    """
    queryset = CommonProblemModel.objects.all()
    serializer_class = CommonProblemConnectSerializer


class CommonProbleUD(generics.UpdateAPIView, generics.DestroyAPIView, generics.ListAPIView):
    """
    获取常见问题详细信息 删除 修改 常见问题
    """
    queryset = CommonProblemModel.objects.filter()
    serializer_class = CommonProblemConnectSerializer
    permission_validate = False

    def get(self, request, *args, **kwargs):
        # _common_problem = CommonProblemModel.objects.get(pk=kwargs['pk'])
        _common_problem = get_object_or_404(CommonProblemModel, pk=kwargs['pk'])
        _serializer = self.get_serializer(_common_problem)
        return Response(_serializer.data, status=status.HTTP_200_OK)

    def update(self, request, *args, **kwargs):
        _common_problem = get_object_or_404(CommonProblemModel, pk=kwargs['pk'])
        _common_problem.title = request.POST['title']
        _common_problem.content = request.POST['content']
        _common_problem.save()
        _serializer = self.get_serializer(_common_problem)
        return Response('success', status=status.HTTP_200_OK)

    def destroy(self, request, *args, **kwargs):
        _common_problem = get_object_or_404(CommonProblemModel, pk=kwargs['pk'])
        _common_problem.is_delete = True
        _common_problem.save()
        _serializer = self.get_serializer(_common_problem)
        return Response('success', status=status.HTTP_200_OK)


class GetInformationList(generics.ListAPIView):
    """
    获取所有资讯的分页 type 1:"富文本" 2:"链接"
    request.query_params.get('pageSize')
    request.query_params.get('pageNo')
    """
    queryset = Information.objects.filter(is_delete=False).order_by('-is_top', 'order')
    serializer_class = InformationSerializer
    pagination_class = LuckyScportPagination


class GetInformationDetail(generics.ListAPIView):
    """
    获取对应资讯的详情
    """
    queryset = Information.objects.all()
    serializer_class = InformationSerializer

    def list(self, request, *args, **kwargs):
        _id = kwargs.get('PK')
        return_dict = {}
        try:
            _info = Information.objects.get(pk=_id)
            _info.read_number = _info.read_number + 1
            _info.save()
            serializer = InformationSerializer(_info)
            return Response(serializer.data, status=status.HTTP_200_OK)
        except:
            return_dict['detail'] = {"message": "资讯为找到"}
            return Response(return_dict, status=status.HTTP_400_BAD_REQUEST)


class GetUserInfoDetail(generics.ListAPIView):
    """
    获取用户信息
    """
    queryset = UserInfo.objects.all()
    serializer_class = UserInfoSerializer

    def get(self, request, *args, **kwargs):
        _id = request.app_user.userinfo.id
        try:
            _user = UserInfo.objects.get(pk=_id)
            serializer = UserInfoSerializer(_user)
            return Response(serializer.data, status=status.HTTP_200_OK)
        except Exception as e:
            e.__repr__()
            return Response({"message": "用户信息未找到"}, status=status.HTTP_200_OK)


class GetUserIsSign(generics.ListAPIView):
    """
    判断用户当天是否已经签到
    """
    queryset = UserInfo.objects.all()
    serializer_class = UserInfoSerializer

    def get(self, request, *args, **kwargs):
        _id = request.app_user.userinfo.id
        _now = Get_Now()
        return_dict = {}
        try:
            _sign = UserSign.objects.get(sign_date=_now, user_id=_id)
            return_dict['detail'] = {"": ""}
            return Response(return_dict, status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            return_dict['result'] = {"": ""}
            return Response(return_dict, status=status.HTTP_200_OK)


class PostConnection(generics.CreateAPIView):
    """
    连接智能衣后创建连接记录
    """
    queryset = ConnectionRecord.objects.all()
    serializer_class = PostCreateConnectionSerializer

    def create(self, request, *args, **kwargs):
        data = request.data
        _user = request.app_user.userinfo.id
        _type = data.get('type')
        return_dict = {}
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid(raise_exception=True):
            _connection = ConnectionRecord()
            _connection.user_id = _user
            _connection.save()
            _connection_type = ConnectionTypeRecord()
            _connection_type.type = _type
            _connection_type.connect_id = _connection.id
            _connection_type.user_id = _user
            _connection_type.save()
            _serializer = ConnectionRecordSerializer(_connection)
            addExpMsg = addExp(request.app_user.userinfo, 5)
            return_dict['result'] = {"point": addExpMsg, "connection": _serializer.data}
            return Response(return_dict, status=status.HTTP_200_OK)


class PauseTrain(generics.CreateAPIView):
    """
    暂停训练 id
    """

    def post(self, request, *args, **kwargs):
        # 计算connetion连接时间
        _id = request.data['id']
        _userinfo = request.app_user.userinfo
        _connection = ConnectionRecord.objects.get(pk=_id)
        this_train_time = (datetime.datetime.now() - _connection.pre_start_time).total_seconds()
        if _connection.duration:
            _connection.duration = _connection.duration + this_train_time
        else:
            _connection.duration = this_train_time
        _connection.save()

        _userinfo.total_sport_time = _userinfo.total_sport_time + _connection.duration
        _userinfo.total_week_sport_time = _userinfo.total_week_sport_time + _connection.duration
        _userinfo.total_day_sport_time = _userinfo.total_day_sport_time + _connection.duration
        _userinfo.save()

        # 2 将connectionType record 结束
        _connection_type = ConnectionTypeRecord.objects.filter(end_time__isnull=True, connect=_connection)
        for _type in _connection_type:
            _type.end_time = datetime.datetime.now()
            _type.duration = (_type.end_time - _type.start_time).total_seconds()
            _type.save()
        return Response(status=status.HTTP_200_OK)


class ContinueTrain(generics.CreateAPIView):
    """
    继续训练 id,type
    """

    def post(self, request, *args, **kwargs):
        # 计算connetion连接时间
        data = request.data
        _id = data['id']
        _type = data.get('type')
        _connection = ConnectionRecord.objects.get(pk=_id)
        _connection.pre_start_time = datetime.datetime.now()
        _connection.save()

        # 新建训练记录
        _connection_type = ConnectionTypeRecord()
        _connection_type.type = _type
        _connection_type.connect_id = _connection.id
        _connection_type.user_id = request.app_user.userinfo.id
        _connection_type.save()
        return Response(status=status.HTTP_200_OK)


class GetHistoryConnectionRecord(generics.ListAPIView):
    """
    获取历史连接记录

    request.query_params.get('pageSize')
    request.query_params.get('pageNo')
    """
    queryset = ConnectionRecord.objects.filter(Q(data_package__isnull=False),
                                               Q(avg_heart_rate__gt=0) | Q(max_heart_rate__gt=0) | Q(
                                                   min_heart_rate__gt=0))
    serializer_class = HistoryConnectionRecordSerializer

    def list(self, request, *args, **kwargs):
        _user = request.app_user.userinfo.id
        _info_list = ConnectionRecord.objects.filter(Q(data_package__isnull=False) & Q(user_id=_user),
                                                     Q(avg_heart_rate__gt=0) | Q(max_heart_rate__gt=0) | Q(
                                                         min_heart_rate__gt=0))
        _pageSize = request.query_params.get('pageSize')
        _pageNum = request.query_params.get('pageNo')
        _list = page_info(HistoryConnectionRecordSerializer(_info_list, many=True).data, _pageSize, _pageNum)
        return Response(_list, status=status.HTTP_200_OK)


class GetMyConnectionRecord(generics.ListAPIView):
    """
    获取个人的本周走运时长和分类连接时长
    type:0 周
    type:1 总
    """
    queryset = UserInfo.objects.all()
    serializer_class = ConnectionUserInfoSerializer

    def get(self, request, *args, **kwargs):
        _user = request.app_user.userinfo.id
        try:
            _type = int(request.query_params.get('type'))
            if _type == 0:
                user_info = UserInfo.objects.get(pk=_user)
                _serializers = ConnectionUserInfoSerializer(user_info)
                return Response(_serializers.data, status=status.HTTP_200_OK)
            else:
                user_info = UserInfo.objects.get(pk=_user)
                _serializers = ConnectionTotalUserInfoSerializer(user_info)
                return Response(_serializers.data, status=status.HTTP_200_OK)
        except Exception as e:
            return Response(e.__repr__(), status=status.HTTP_400_BAD_REQUEST)


class PostChangeConnection(generics.CreateAPIView):
    """
    智能衣更换连接类别
    """
    queryset = ConnectionRecord.objects.all()
    serializer_class = PostChangeConnectionSerializer

    def create(self, request, *args, **kwargs):
        data = request.data
        _id = data.get('id')
        _type = data.get('type')
        _user = request.app_user.userinfo.id
        return_dict = {}
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid(raise_exception=True):
            try:
                _connection_type = ConnectionTypeRecord.objects.filter(end_time__isnull=True, connect_id=_id)
                for _types in _connection_type:
                    _types.end_time = datetime.datetime.now()
                    _types.duration = (_types.end_time - _types.start_time).total_seconds()
                    _types.save()
                _connection_type = ConnectionTypeRecord()
                _connection_type.type = _type
                _connection_type.connect_id = _id
                _connection_type.user_id = _user
                _connection_type.save()
                return_dict['result'] = {"message": "切换类别成功"}
                return Response(return_dict, status=status.HTTP_201_CREATED)
            except Exception as e:
                return_dict['detail'] = {"message": "连接记录未找到"}
                return Response(return_dict, status=status.HTTP_400_BAD_REQUEST)


class PostEndConnection(generics.CreateAPIView):
    """
    智能衣使用结束清楚记录
    PK是连接记录的主键 user是当前登录用户信息记录的主键
    """
    queryset = ConnectionRecord.objects.all()
    serializer_class = PostEndConnectionSerializer

    def create(self, request, *args, **kwargs):
        _id = kwargs.get('PK')
        _user = request.app_user.userinfo.id
        data = request.data
        _avg = data.get('avg')
        _max = data.get('max')
        _min = data.get('min')
        _package = data.get('package')
        return_dict = {}
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid(raise_exception=True):
            try:
                _userinfo = UserInfo.objects.get(pk=_user)
                _connection = ConnectionRecord.objects.get(pk=_id)
                _connection_type = ConnectionTypeRecord.objects.filter(end_time__isnull=True, connect=_connection)
                for _type in _connection_type:
                    _type.end_time = datetime.datetime.now()
                    _type.duration = (_type.end_time - _type.start_time).total_seconds()
                    _type.save()
                _connection.end_time = datetime.datetime.now()
                _connection.duration = (_connection.end_time - _connection.pre_start_time).total_seconds()
                _connection.avg_heart_rate = _avg
                _connection.max_heart_rate = _max
                _connection.min_heart_rate = _min
                _connection.data_package = _package
                _connection.save()
                _connections = ConnectionRecord.objects.filter(user=_userinfo)
                if _userinfo.medals is None:
                    if len(_connections) >= 30:
                        _userinfo.medals = '3'
                    else:
                        pass
                else:
                    if '3' in _userinfo.medals:
                        pass
                    else:
                        if len(_connections) >= 30:
                            _userinfo.medals = _userinfo.medals + ',3'
                        else:
                            pass
                _userinfo.total_sport_time = _userinfo.total_sport_time + _connection.duration
                _userinfo.total_week_sport_time = _userinfo.total_week_sport_time + _connection.duration
                _userinfo.total_day_sport_time = _userinfo.total_day_sport_time + _connection.duration
                _userinfo.save()
                _serializer = ConnectionRecordSerializer(_connection)
                return Response(_serializer.data, status=status.HTTP_201_CREATED)
            except Exception as e:
                return_dict['detail'] = {"message": "连接记录未找到"}
                return Response(return_dict, status=status.HTTP_400_BAD_REQUEST)


class PostShare(generics.CreateAPIView):
    """
    新建分享记录
    """
    queryset = ShareRecord.objects.all()
    serializer_class = UserInfoSerializer

    def create(self, request, *args, **kwargs):
        _id = kwargs.get('affair')
        _user = request.app_user.userinfo
        _share = ShareRecord()
        _now = Get_Now()
        return_dict = {}
        _share.user = _user
        _share.affair_id = _id
        _share.save()
        _shares = ShareRecord.objects.filter(user=_user)
        if _user.medals is None:
            if len(_shares) >= 30:
                _user.medals = '2'
            else:
                pass
        else:
            if '2' in _user.medals:
                pass
            else:
                if len(_shares) >= 30:
                    _user.medals = _user.medals + ',2'
        _serializer = UserInfoSerializer(_user)
        return_dict['result'] = {"point": addExp(_user, 3), "share": _serializer.data}
        return Response(return_dict, status=status.HTTP_200_OK)


class postAndGetUserBodyData(generics.CreateAPIView):
    """
    上传用户的身体信息，并返回体重和体脂
    """
    queryset = BodyData.objects.all()
    serializer_class = PostSaveUserBodyInfoSerializer

    def create(self, request, *args, **kwargs):
        data = request.data
        _app_user = request.app_user
        _full_str = data['fullStr']
        # try:
        # _full_str_dict = eval(eval(_full_str))
        _full_str_dict = eval(_full_str)
        # except Exception as e:
        #     print(e)
        return_dict = {}

        _bmi = _full_str_dict['bmi']
        _fat_percentage = _full_str_dict['fatPercentage']
        _fat_weight = _full_str_dict['fatWeight']
        _water_weight = _full_str_dict['waterWeight']
        _visceral_fat_percentage = _full_str_dict['visceralFatPercentage']
        _muscle_weight = _full_str_dict['muscleWeight']
        _bmr = _full_str_dict['bmr']
        _bone_weight = _full_str_dict['boneWeight']
        _fat_level = _full_str_dict['fatLevel']
        _lbm = _full_str_dict['lbm']
        _body_age = _full_str_dict['bodyAge']
        _fat_control = _full_str_dict['fatControl']
        _fatty_liver_risk = _full_str_dict['fattyLiverRisk']
        _m_smm = _full_str_dict['m_smm']
        _muscle_control = _full_str_dict['muscleControl']
        _physique = _full_str_dict['physique']
        _score = _full_str_dict['score']
        _standard_fat_percentage = _full_str_dict['standardFatPercentage']
        _water_percentage = _full_str_dict['waterPercentage']
        _weight_control = _full_str_dict['weightControl']
        _bone_muscle_weight = _full_str_dict['boneMuscleWeight']
        _protein_weight = _full_str_dict['proteinWeight']
        _sw = _full_str_dict['sw']
        _weight = _full_str_dict['weight']

        _bmi_max = _full_str_dict['bmiMax']
        _bmi_min = _full_str_dict['bmiMin']
        _bone_muscle_weight_max = _full_str_dict['boneMuscleWeightMax']
        _bone_muscle_weight_min = _full_str_dict['boneMuscleWeightMin']
        _bone_weight_max = _full_str_dict['boneWeightMax']
        _bone_weight_min = _full_str_dict['boneWeightMin']
        _fat_percentage_max = _full_str_dict['fatPercentageMax']
        _fat_percentage_min = _full_str_dict['fatPercentageMin']
        _fat_weight_max = _full_str_dict['fatWeightMax']
        _fat_weight_min = _full_str_dict['fatWeightMin']
        _muscle_weight_max = _full_str_dict['muscleWeightMax']
        _muscle_weight_min = _full_str_dict['muscleWeightMin']
        _protein_weight_max = _full_str_dict['proteinWeightMax']
        _protein_weight_min = _full_str_dict['proteinWeightMin']
        _sw_max = _full_str_dict['swMax']
        _sw_min = _full_str_dict['swMin']
        _visceral_fat_percentage_max = _full_str_dict['visceralFatPercentageMax']
        _visceral_fat_percentage_min = _full_str_dict['visceralFatPercentageMin']
        _water_weight_max = _full_str_dict['waterWeightMax']
        _water_weight_min = _full_str_dict['waterWeightMin']
        _weight_max = _full_str_dict['weightMax']
        _weight_min = _full_str_dict['weightMin']

        serializer = self.get_serializer(data=request.data)
        _create_time = datetime.datetime.now()
        try:
            # if serializer.is_valid(raise_exception=True):
            try:
                # try:
                #     _user = BodyData.objects.get(user=_app_user.userinfo)
                #     _user.user = _app_user.userinfo
                #     _user.bmi = _bmi
                #     _user.fat_percentage = _fat_percentage
                #     _user.water_weight = _water_weight
                #     _user.visceral_fat_percentage = _visceral_fat_percentage
                #     _user.muscle_weight = _muscle_weight
                #     _user.bmr = _bmr
                #     _user.bone_weight = _bone_weight
                #     _user.fat_level = _fat_level
                #     _user.save()
                #     _serializer = PostSaveUserBodyInfoSerializer(_user)
                #
                #     _chart_list_data=BodyData.objects.filter()
                #
                #     return Response(_serializer.data, status=status.HTTP_201_CREATED)
                # except Exception as e:
                _user = BodyData()
                _user.user = _app_user.userinfo
                _user.bmi = float(_bmi)
                _user.fat_percentage = float(_fat_percentage)
                _user.fat_weight = float(_fat_weight)
                _user.water_weight = float(_water_weight)
                _user.visceral_fat_percentage = float(_visceral_fat_percentage)
                _user.muscle_weight = float(_muscle_weight)
                _user.bmr = float(_bmr)
                _user.bone_weight = float(_bone_weight)
                _user.fat_level = float(_fat_level)
                _user.lbm = float(_lbm)
                _user.body_age = float(_body_age)
                _user.fat_control = float(_fat_control)
                _user.fatty_liver_risk = float(_fatty_liver_risk)
                _user.m_smm = float(_m_smm)
                _user.muscle_control = float(_muscle_control)
                _user.physique = float(_physique)
                _user.score = float(_score)
                _user.standard_fat_percentage = float(_standard_fat_percentage)
                _user.water_percentage = float(_water_percentage)
                _user.weight_control = float(_weight_control)
                _user.bone_muscle_weight = float(_bone_muscle_weight)
                _user.muscle_weight = float(_muscle_weight)
                _user.protein_weight = float(_protein_weight)
                _user.sw = float(_sw)
                _user.weight = float(_weight)

                _user.bmi_max = float(_bmi_max)
                _user.bmi_min = float(_bmi_min)
                _user.bone_muscle_weight_max = float(_bone_muscle_weight_max)
                _user.bone_muscle_weight_min = float(_bone_muscle_weight_min)
                _user.bone_weight_max = float(_bone_weight_max)
                _user.bone_weight_min = float(_bone_weight_min)
                _user.fat_percentage_max = float(_fat_percentage_max)
                _user.fat_percentage_min = float(_fat_percentage_min)
                _user.fat_weight_max = float(_fat_weight_max)
                _user.fat_weight_max = float(_fat_weight_min)
                _user.muscle_weight_max = float(_muscle_weight_max)
                _user.muscle_weight_min = float(_muscle_weight_min)
                _user.protein_weight_max = float(_protein_weight_max)
                _user.protein_weight_min = float(_protein_weight_min)
                _user.sw_max = float(_sw_max)
                _user.sw_min = float(_sw_min)
                _user.visceral_fat_percentage_max = float(_visceral_fat_percentage_max)
                _user.visceral_fat_percentage_min = float(_visceral_fat_percentage_min)
                _user.water_weight_max = float(_water_weight_max)
                _user.water_weight_min = float(_water_weight_min)
                _user.weight_max = float(_weight_max)
                _user.weight_min = float(_weight_min)

                _user_last_time = BodyData.objects.filter(user_id=_app_user.userinfo.id).order_by('-start_time').first()
                if _user_last_time is not None:
                    if _user_last_time.used_count is not None:
                        count = _user_last_time.used_count
                    else:
                        count = BodyData.objects.filter(
                            user_id=_app_user.userinfo.id).count()  # need to be optimized!!!
                    try:
                        if _user_last_time.fat_percentage_avg_sofar:
                            _user.fat_percentage_avg_sofar = (_user_last_time.fat_percentage_avg_sofar * count + float(
                                _user.fat_percentage)) / (count + 1)
                        else:
                            _user.fat_percentage_avg_sofar = _user.fat_percentage

                        if _user_last_time.weight_avg_sofar:
                            _user.weight_avg_sofar = (
                                                             _user_last_time.weight_avg_sofar * count + float(
                                                         _user.weight)) / (
                                                             count + 1)
                        else:
                            _user.weight_avg_sofar = _user.weight
                        _user.used_count = count + 1
                    except Exception as e:
                        print(e)
                else:
                    _user.used_count = 1
                    _user.weight_avg_sofar = float(_weight)
                    _user.fat_percentage_avg_sofar = float(_fat_percentage)

                # reserve two digits after decimal
                _user.weight_avg_sofar = round(float(_user.weight_avg_sofar), 2)
                _user.fat_percentage_avg_sofar = round(float(_user.fat_percentage_avg_sofar), 2)

                _user.save()
                _serializer = PostSaveUserBodyInfoSerializer(_user)
                _all_list = BodyData.objects.filter(user_id=_app_user.userinfo.id).order_by('-start_time')
                _chart_list = []
                for a in _all_list:
                    _item = {}
                    _item['start_time'] = a.start_time
                    _item['faPercentage'] = a.fat_percentage
                    _item['weight'] = a.weight
                    _item['physique'] = a.physique
                    _chart_list.append(_item)

                return Response(_chart_list, status=status.HTTP_201_CREATED)
            except Exception as e:
                return_dict['detail'] = {"message": "服务器异常"}
                return Response(return_dict, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        except Exception as e:
            return_dict['detail'] = {"message": "服务器异常"}
            return Response(return_dict, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class getUserBodyDataList(generics.ListAPIView):
    """
    获取体重体脂列表
    需要传递参数：num
    """
    queryset = BodyData.objects.all()
    serializer_class = GetBodyDataListSerializer

    def list(self, request, *args, **kwargs):
        data = request.data
        _app_user = request.app_user
        _num = int(request.query_params.get('num'))
        return_dict = {}
        try:
            _all_list = BodyData.objects.filter(user_id=_app_user.userinfo.id).order_by('-start_time')[:_num]
            # _chart_list = []
            # for a in _all_list:
            #     _item = {}
            #     _item['start_time'] = a.start_time
            #     _item['fat_percentage'] = a.fat_percentage
            #     _item['weight'] = a.weight
            #     # _item['physique'] = a.physique
            #     _chart_list.append(_item)
            _serializer = GetBodyDataListSerializer(_all_list, many=True)
            return Response(_serializer.data, status=status.HTTP_200_OK)

        except Exception as e:
            return_dict['detail'] = {"message": "服务器异常"}
            return Response(return_dict, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class GetBodyDataDetailAll(generics.ListAPIView):
    """
    获取所有的体脂称历史信息

 request.query_params.get('pageSize')
request.query_params.get('pageNo')
    """
    queryset = BodyData.objects.all()
    serializer_class = BodyDataSerializer

    def list(self, request, *args, **kwargs):
        data = request.data
        _app_user = request.app_user
        _info_list = BodyData.objects.filter(user_id=_app_user.userinfo.id).order_by('-start_time')
        _pageSize = request.query_params.get('pageSize')
        _pageNum = request.query_params.get('pageNo')
        _info = BodyDataSerializer(_info_list, many=True)
        _info_data = _info.data
        _list = page_info(_info_data, _pageSize, _pageNum)
        return Response(_list, status=status.HTTP_200_OK)


class GetBodyDataDetail(generics.ListAPIView):
    """
    获取单次体脂称信息
    需要PK参数
    """
    queryset = Training.objects.all()
    serializer_class = BodyDataSerializer

    def list(self, request, *args, **kwargs):
        _id = kwargs.get('PK')
        return_dict = {}
        try:
            _list = BodyData.objects.get(pk=_id)
            _serializer = BodyDataSerializer(_list)
            return Response(_serializer.data, status=status.HTTP_200_OK)
        except:
            return_dict['detail'] = {"message": "未找到该次记录"}
            return Response(return_dict, status=status.HTTP_200_OK)


class UserBluetoothDetail(generics.UpdateAPIView):
    """
    重新绑定蓝牙信息
    """

    def put(self, request, *args, **kwargs):
        _app_user = request.app_user
        _user_info = _app_user.userinfo
        _user_info.bluetooth_key = kwargs.get('KEY')
        _user_info.save()
        return Response('success', status=status.HTTP_200_OK)


# class postAndGetUserBodyData(generics.CreateAPIView):
#     """
#     上传用户的身体信息，并返回体重和体脂
#     """
#     queryset = BodyData.objects.all()
#     serializer_class = PostSaveUserBodyInfoSerializer
#
#     def create(self, request, *args, **kwargs):
#         data = request.data
#         _app_user = request.app_user
#         return_dict = {}
#         _bmi = data.get('bmi')
#         _fat_percentage = data.get('fat_percentage')
#         _water_weight = data.get('water_weight')
#         _visceral_fat_percentage = data.get('visceral_fat_percentage')
#         _muscle_weight = data.get('muscle_weight')
#         _bmr = data.get('bmr')
#         _bone_weight = data.get('bone_weight')
#         _fat_level = data.get('fat_level')
#         _lbm = data.get('lbm')
#         _body_age = data.get('body_age')
#         _fat_control = data.get('fat_control')
#         _fatty_liver_risk = data.get('fatty_liver_risk')
#         _m_smm = data.get('m_smm')
#         _muscle_control = data.get('muscle_control')
#         _physique = data.get('physique')
#         _score = data.get('score')
#         _standard_fat_percentage = data.get('standard_fat_percentage')
#         _water_percentage = data.get('water_percentage')
#         _weight_control = data.get('weight_control')
#         _bone_muscle_weight = data.get('bone_muscle_weight')
#         _protein_weight = data.get('protein_weight')
#         _sw = data.get('sw')
#         _weight = data.get('weight')
#
#         _bmi_max = data.get('bmi_max')
#         _bmi_min = data.get('bmi_min')
#         _bone_muscle_weight_max = data.get('bone_muscle_weight_max')
#         _bone_muscle_weight_min = data.get('bone_muscle_weight_min')
#         _bone_weight_max = data.get('bone_weight_max')
#         _bone_weight_min = data.get('bone_weight_min')
#         _fat_percentage_max = data.get('fat_percentage_max')
#         _fat_percentage_min = data.get('fat_percentage_min')
#         _fat_weight_max = data.get('fat_weight_max')
#         _fat_weight_min = data.get('fat_weight_min')
#         _muscle_weight_max = data.get('muscle_weight_max')
#         _muscle_weight_min = data.get('muscle_weight_min')
#         _protein_weight_max = data.get('protein_weight_max')
#         _protein_weight_min = data.get('protein_weight_min')
#         _sw_max = data.get('sw_max')
#         _sw_min = data.get('sw_min')
#         _visceral_fat_percentage_max = data.get('visceral_fat_percentage_max')
#         _visceral_fat_percentage_min = data.get('visceral_fat_percentage_min')
#         _water_weight_max = data.get('water_weight_max')
#         _water_weight_min = data.get('water_weight_min')
#         _weight_max = data.get('weight_max')
#         _weight_min = data.get('weight_min')
#
#         serializer = self.get_serializer(data=request.data)
#         _create_time = datetime.datetime.now()
#         try:
#             # if serializer.is_valid(raise_exception=True):
#             try:
#                 _user = BodyData()
#                 _user.user = _app_user.userinfo
#                 _user.bmi = _bmi
#                 _user.fat_percentage = _fat_percentage
#                 _user.water_weight = _water_weight
#                 _user.visceral_fat_percentage = _visceral_fat_percentage
#                 _user.muscle_weight = _muscle_weight
#                 _user.bmr = _bmr
#                 _user.bone_weight = _bone_weight
#                 _user.fat_level = _fat_level
#                 _user.lbm = _lbm
#                 _user.body_age = _body_age
#                 _user.fat_control = _fat_control
#                 _user.fatty_liver_risk = _fatty_liver_risk
#                 _user.m_smm = _m_smm
#                 _user.muscle_control = _muscle_control
#                 _user.physique = _physique
#                 _user.score = _score
#                 _user.standard_fat_percentage = _standard_fat_percentage
#                 _user.water_percentage = _water_percentage
#                 _user.weight_control = _weight_control
#                 _user.bone_muscle_weight = _bone_muscle_weight
#                 _user.muscle_weight = _muscle_weight
#                 _user.protein_weight = _protein_weight
#                 _user.sw = _sw
#                 _user.weight = _weight
#
#                 _user.bmi_max = _bmi_max
#                 _user.bmi_min = _bmi_min
#                 _user.bone_muscle_weight_max = _bone_muscle_weight_max
#                 _user.bone_muscle_weight_min = _bone_muscle_weight_min
#                 _user.bone_weight_max = _bone_weight_max
#                 _user.bone_weight_min = _bone_weight_min
#                 _user.bone_weight_min = _fat_percentage_max
#                 _user.fat_percentage_min = _fat_percentage_min
#                 _user.fat_weight_max = _fat_weight_max
#                 _user.fat_weight_max = _fat_weight_min
#                 _user.muscle_weight_max = _muscle_weight_max
#                 _user.muscle_weight_min = _muscle_weight_min
#                 _user.protein_weight_max = _protein_weight_max
#                 _user.protein_weight_min = _protein_weight_min
#                 _user.sw_max = _sw_max
#                 _user.sw_min = _sw_min
#                 _user.visceral_fat_percentage_max = _visceral_fat_percentage_max
#                 _user.visceral_fat_percentage_min = _visceral_fat_percentage_min
#                 _user.water_weight_max = _water_weight_max
#                 _user.water_weight_min = _water_weight_min
#                 _user.weight_max = _weight_max
#                 _user.weight_min = _weight_min
#
#                 _user_last_time = BodyData.objects.filter(user_id=_app_user.userinfo.id).order_by('-start_time').first()
#                 if _user_last_time.used_count is not None:
#                     count = _user_last_time.used_count
#                 else:
#                     count = BodyData.objects.filter(user_id=_app_user.userinfo.id).count()  # need to be optimized!!!
#                 try:
#                     if _user_last_time.fat_percentage_avg_sofar:
#                         _user.fat_percentage_avg_sofar = (_user_last_time.fat_percentage_avg_sofar * count + float(
#                             _user.fat_percentage)) / (count + 1)
#                     else:
#                         _user.fat_percentage_avg_sofar = _user.fat_percentage
#
#                     if _user_last_time.weight_avg_sofar:
#                         _user.weight_avg_sofar = (_user_last_time.weight_avg_sofar * count + float(_user.weight)) / (count + 1)
#                     else:
#                         _user.weight_avg_sofar = _user.weight
#                     _user.used_count = count + 1
#                 except Exception as e:
#                     print(e)
#
#                 _user.save()
#                 _serializer = PostSaveUserBodyInfoSerializer(_user)
#                 _all_list = BodyData.objects.filter(user_id=_app_user.userinfo.id).order_by('start_time')
#                 _chart_list = []
#                 for a in _all_list:
#                     _item = {}
#                     _item['start_time'] = a.start_time
#                     _item['fat_percentage'] = a.fat_percentage
#                     _item['weight'] = a.weight
#                     _item['physique'] = a.physique
#                     _chart_list.append(_item)
#
#                 return Response(_chart_list, status=status.HTTP_201_CREATED)
#             except Exception as e:
#                 return_dict['detail'] = {"message": "服务器异常"}
#                 return Response(return_dict, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
#         except Exception as e:
#             return_dict['detail'] = {"message": "服务器异常"}
#             return Response(return_dict, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class VersionInfo(generics.RetrieveAPIView):
    permission_validate = False

    def get(self, request, *args, **kwargs):
        try:
            _app_version = AppVersionModel.objects.get(version=kwargs.get('VERSION'))
        except AppVersionModel.DoesNotExist:
            # return Response('no version info', status=status.HTTP_400_BAD_REQUEST)
            return Response(status=status.HTTP_200_OK)
        _app_version_serializer = AppVersionSerializer(_app_version)
        return Response(_app_version_serializer.data, status=status.HTTP_200_OK)


class GetHardwareVersion(generics.CreateAPIView):
    """
    获取是否有最新硬件版本 category manufacture hw_version fw_version
    """
    permission_validate = False

    def post(self, request, *args, **kwargs):
        data = request.data
        _category = data['category']
        _manufacture = data['manufacture']
        _hw_version = data['hw_version']
        _fw_version = data['fw_version']

        _hard_version = HardwareVersionModel.objects.filter(category=_category, manufacture=_manufacture,
                                                            hw_version=_hw_version,
                                                            fw_version__gt=_fw_version, is_delete=False).order_by(
            '-fw_version').first()

        if '1.0.5' == _fw_version:
            print('category:' + _category + "manufacture:" + _manufacture,
                  "hw_version:" + _hw_version + "fw_version:" + _fw_version, "hard_version" + _hard_version)

        if _hard_version:

            # 有新版本 返回版本信息
            return Response(
                {"hardware_id": _hard_version.id, "have_new_version": True, "version_no": _hard_version.fw_version,
                 "url": "http://sport.zouyunjs.com/lucky-sport-hardwares/" + _hard_version.hardware_url},
                status=status.HTTP_200_OK)
        else:
            return Response({"have_new_version": False, "version_no": "", "url": ""}, status=status.HTTP_200_OK)


class PutIdcardInfo(generics.CreateAPIView):
    """
    更新用户身份证信息 idcard idcardImgBg idcardImgFg
    """

    def post(self, request, *args, **kwargs):
        _app_user = request.app_user
        _user_info = _app_user.userinfo
        _user_info.idcard_no = request.data.get('idcard')
        _user_info.idcard_img_bg = request.data.get('idcardImgBg')
        _user_info.idcard_img_fg = request.data.get('idcardImgFg')
        # 审核 ((0,'未审核'),(1,'已审核'),(2,'审核失败'),(3,'待审核'))
        _user_info.is_certification = 3
        _user_info.save()
        return Response('success', status=status.HTTP_200_OK)


class getUserCardInfo(generics.RetrieveAPIView):
    """
    获取用户身份证及认证信息
    """

    def get(self, request, *args, **kwargs):
        _app_user = request.app_user
        _user_info = _app_user.userinfo
        _serializer = UserCardInfoSerializer(_user_info)
        return Response(_serializer.data, status=status.HTTP_200_OK)


class PostSuggesion(generics.CreateAPIView):
    """
    用户意见保存 内容content
    """
    serializer_class = SuggestionRecordSerialiezer
    queryset = SuggestionRecordModel.objects.all()

    def post(self, request, *args, **kwargs):
        _suggestion = SuggestionRecordModel()
        _suggestion.content = request.data['content']
        _suggestion.user = request.app_user.userinfo
        _suggestion.save()
        return Response("success", status=status.HTTP_201_CREATED)


class GetNewAffairStatus(generics.CreateAPIView):
    """
    获取是否有新帖子更新
    """

    def get(self, request, *args, **kwargs):
        _user_info = request.app_user.userinfo
        _new_count = AffairsRecord.objects.values('id').filter(is_delete=False,
                                                               create_time__gt=_user_info.flush_affair_time).filter(
            ~Q(user=_user_info)).aggregate(
            Count('id'))['id__count']
        if _new_count > 0:
            return Response({'has_new': True, 'count': _new_count}, status=status.HTTP_200_OK)
        else:
            return Response({'has_new': False}, status=status.HTTP_200_OK)


class GetHomePageStatus(generics.CreateAPIView):
    """
    获取是否有新评论/点赞
    """

    def get(self, request, *args, **kwargs):
        _user_info = request.app_user.userinfo
        # 点赞
        _good_count = ThumbRecord.objects.values('id').filter(operation_time__gt=_user_info.flush_homepage_time,
                                                              affair__user__id=_user_info.id,
                                                              ).filter(~Q(user=_user_info)).aggregate(
            Count('id'))['id__count']
        # ~Q(user_id=_user_info.id)
        _commont_count = CommentRecord.objects.values('id').filter(operation_time__gt=_user_info.flush_homepage_time,
                                                                   affair__user__id=_user_info.id).filter(
            ~Q(user=_user_info)).aggregate(
            Count('id'))['id__count']
        _total_count = _commont_count + _good_count
        if _total_count > 0:
            return Response({'has_new': True, 'count': _total_count}, status=status.HTTP_200_OK)
        else:
            return Response({'has_new': False}, status=status.HTTP_200_OK)


class PostUserVersion(generics.CreateAPIView):
    """
    上传用户版本 type hardware_id app_version
    """

    def post(self, request, *args, **kwargs):
        _user_info = request.app_user.userinfo
        _hardware_type = request.data['type']
        _hardware_id = request.data['hardware_id']
        _app_version = request.data['app_version']
        if _hardware_type == '00':
            _user_info.hardware_00_version_id = _hardware_id
        elif _hardware_type == '01':
            _user_info.hardware_01_version_id = _hardware_id
        elif _hardware_type == '02':
            _user_info.hardware_02_version_id = _hardware_id
        elif _hardware_type == '03':
            _user_info.hardware_03_version_id = _hardware_id
        _user_info.app_version = _app_version
        _user_info.save()
        return Response("上传成功", status=status.HTTP_200_OK)


class ResetRunningTime(generics.CreateAPIView):
    def post(self, request, *args, **kwargs):
        _user_info = list(UserInfo.objects.all())
        for __user_info in _user_info:
            _connection_record = list(ConnectionRecord.objects.filter(user=__user_info))
            for __connection_record in _connection_record:
                _duration = ConnectionTypeRecord.objects.filter(connect=__connection_record,
                                                                duration__lt=18000).aggregate(Sum('duration')).get(
                    'duration__sum', 0)
                if _duration is not None:
                    print(__connection_record.duration, "|", _duration)
                    __connection_record.duration = _duration
                    __connection_record.save()

            _duration = ConnectionRecord.objects.filter(user=__user_info, duration__lt=18000).aggregate(
                Sum('duration')).get('duration__sum', 0)
            if _duration is not None:
                __user_info.total_sport_time = _duration
                __user_info.save()
                # print(__user_info.total_sport_time ,"|",_duration)


class AddSgin(generics.CreateAPIView):
    permission_validate = False

    def post(self, request, *args, **kwargs):
        _user_info = list(UserInfo.objects.all())
        for __user_info in _user_info:
            _sign = UserSign()
            _sign.user_id = __user_info.id
            _sign.sign_date = '20180514'
            _sign.sign_day = '14'
            _sign.sign_month = '5'
            _sign.sign_year = '2018'
            _sign.save()


class PostUserBodyDimension(generics.CreateAPIView):
    """
    保存用户用户身体维度信息 UserBodyDimension
    """
    serializer_class = UserBodyDimensionSerializer

    def post(self, request, *args, **kwargs):
        _data = request.data.copy()
        _data['user'] = request.app_user.userinfo.id
        serializer = UserBodyDimensionSerializer(data=_data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


class UserBodyDemendionList(generics.ListAPIView):
    """
    查询用户身体维度信息
    """
    serializer_class = UserBodyDimensionSerializer

    def get(self, request, *args, **kwargs):
        _page_size = request.query_params.get('pageSize')
        _page_num = request.query_params.get('pageNo')
        _user_body_dimension = UserBodyDimension.objects.filter(user=request.app_user.userinfo, is_delete=False)
        _list = page_info(UserBodyDimensionSerializer(_user_body_dimension, many=True).data, _page_size, _page_num)
        return Response(_list, status=status.HTTP_200_OK)


class UserBodyDemendionDetail(generics.RetrieveAPIView):
    """
    查看详细信息
    """
    serializer_class = UserBodyDimensionSerializer
    queryset = UserBodyDimension.objects.filter(is_delete=False)
